package com.lagou.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 德鲁伊连接池工具类
 * @author Administrator
 */
public class DruidUtils {

    /**
     * 1.dataSource引用
     */
    public static DataSource dataSource = null;

    static {

        try {
            //2.获取配置文件输入流
            InputStream inputStream = DruidUtils.class.
                    getClassLoader().getResourceAsStream("druid.properties");

            //3.加载配置文件
            Properties p  = new Properties();
            p.load(inputStream);

            //4.或者数据库连接池对象
            dataSource =  DruidDataSourceFactory.createDataSource(p);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     *  获取连接
     * @return 返回连接
     */
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放资源
     * @param con 连接
     * @param statement 执行平台
     */
    public static void close(Connection con , Statement statement ){
        if( con != null && statement != null){
            try {
                statement.close();
                con.close(); //归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection con , Statement statement , ResultSet resultSet){
        if( resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        close(con,statement);
    }
}
